<?php

class upload extends MY_Api {
	private $upload_config = null;
	private $thumb_width = 120;
	private $thumb_height = 120;
	
	public function __construct(){
		error_reporting(0);
		parent::__construct();
		$this->config->load('uploads',true);
		$this->upload_config = $this->config->item('uploads');
		$this->load->model('file_model','file');
		$this->load->library('upload',$this->upload_config);
	}
	
	/**
	 * Upload images action
	 * This action just for ajax upload
	 */
	public function do_upload($langkey='cn'){
		$userfield = 'upload';
		$upload_path = $this->_upload_dir($this->upload_config['upload_path']);
		$this->upload->set_upload_path($upload_path);
		if ( !$this->upload->do_upload($userfield) )
		{
			$this->set_error_code(603);
			$this->set_msg($this->upload->display_errors());
		}
		else
		{
			$file_info = $this->upload->data();
			//generate image thumb
			$thumb_config = array(
					'image_library' => 'gd2',
					'source_image'  => $this->upload->upload_path.$file_info['file_name'],
					'new_image'     => $this->upload->upload_path.$file_info['file_name'],
					'maintain_ratio'=> TRUE,
					'create_thumb'  => TRUE,
					'thumb_marker'  => '_thumb',
					'width'         => $this->thumb_width,
					'height'        => $this->thumb_height
			);
			$this->load->library('image_lib',$thumb_config);
			$upload_path = str_replace('../', '/', $upload_path);
			$file_data = array(
					'uid'   => get_uid(),
					'filepath'=>$thumb_config['source_image'],
					'thumbpath'=>$thumb_config['new_image'],
					'timestamp'=> time(),
					);
			if ( !$this->image_lib->resize() ){
				//failed to generate thumb
				//and there is no thumb
				$file_data['thumbpath'] = '';
			}
			if( $this->file->insert($file_data) ){
				$file_data['fid'] = $this->file->db->insert_id();
			}
			$response = $file_data;
		}
		$this->set_data($response);
		$this->output();
	}
	
	/**
	 * Delete an uploaded image
	 */
	public function delete($fid){
		$file  = $this->file->get($fid);
		//the file is not exist
		if ( !isset($file->fid) ){
			$this->set_msg($this->lang->line('error_not_found_this_item'));
		}
		else {
			$status = $this->file->delete($fid);
			$this->set_msg($this->lang->line('oprate_success'));
		}
		$this->output();
	}
	
	/**
	 * Make upload folder function
	 * @param string $upload_dir base upload dir
	 */
	private function _upload_dir($upload_dir){
		$dirstr = $upload_dir.date('Y/m/d');
		if ( !is_dir($dirstr) ){
			mkdir($dirstr,0777,true);
		}
		return $dirstr;
	}
}